
var visibleAscii = "^[\\u0020-\\u007e]*$";

$(document).ready(function () {

    // $.validator.addMethod("regex", function (value, element, params) {
    //     var re = new RegExp(params);
    //     return this.optional(element) || re.test(value);
    // }, "Please enter a valid input.");

    $("#form_login").validate({
        rules: {
            username: {
                required: true,
                pattern: visibleAscii
            },
            password: {
                required: true,
                pattern: visibleAscii,
                rangelength: [6, 64]
            }
        },
        messages: {
            username: {
                required: "请输入用户名",
                pattern: "用户名存在非法字符，请输入正确的用户名"
            },
            password: {
                required: "请输入密码",
                pattern: "密码存在非法字符",
                rangelength: "密码必须为 6 到 64 个字符"
            }
        },
        errorClass: "uk-text-danger",
        errorPlacement: function (error, element) {
            error.insertAfter(element.parent("div"));
        },
        highlight: function (element, errorClass, validClass) {
            $(element).addClass("uk-form-danger");
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).removeClass("uk-form-danger");
        },
        submitHandler: submitLoginForm,
        debug: true
    })
});

function submitLoginForm(form) {
    var rawPassword = $("#form_login_psw")[0].value;
    var encodedPassword = Base64.encode(rawPassword);

    $.ajax({
        url: "/api/auth/login",
        data: {
            username: $("#form_login_username")[0].value.toString(),
            encoded_password: encodedPassword
        },
        type: "POST"
    })
        .done(function (data) {
            window.location.href = "/";
        })
        .fail(function (jqXHR) {
            var response = JSON.parse(jqXHR.responseText);
            if (response != null) {
                if (response.error.code === 216000) {
                    UIkit.notify("账号或密码错误", {status: "danger"});
                } else if (response.error.code % 200000 >= 3000 && response.error.code % 200000 < 4000) {
                    UIkit.notify("参数错误", {status: "danger"});
                }
            }
        })
}